package com.demo.spring.aware;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

@Component
public class MyResourceLoaderAware implements ResourceLoaderAware {
	
	private Properties settings;
	private ResourceLoader loader;
	private static final String SETTINGS_FILE = "classpath:/settings.properties";
	
	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		System.out.println("set resourceLoader: " + resourceLoader);
		this.loader = resourceLoader;
		try {
			FileInputStream inputStream  = new FileInputStream(loader.getResource(SETTINGS_FILE).getFile());
			settings = new Properties();
			settings.load(inputStream);
			inputStream.close();
			System.out.println(getProperty("username"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Properties getSettings() {
		return settings;
	}
	
	public void setProperty(String key,String value){
		settings.setProperty(key, value);
		
	}
	public String getProperty(String key){
		return settings.getProperty(key);
	}
	
	public double getDouble(String key){
		return Double.parseDouble(settings.getProperty(key));
	}
	
	public int getInteger(String key){
		return Integer.parseInt(settings.getProperty(key));
	}
	
	public void save(){
		try {
			OutputStream outputStream = new FileOutputStream(loader.getResource(SETTINGS_FILE).getFile());
			settings.store(outputStream, "");
			outputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
